// 第002个包：npm install vue-router -S
import { createRouter, createWebHashHistory } from "vue-router";
// 第008个包：npm install nprogress -S
// 第008个包：npm install @types/nprogress -D
import nprogress from "nprogress";
import { constantRoutes } from "@/router/routes";
import pinia from "@/store/index.ts";
import useUserStore from "@/store/modules/user.ts";
nprogress.configure({ showSpinner: false });
const userStore = useUserStore(pinia);

// 创建路由实例对象
const router = createRouter({
  // 路由模式（createWebHistory()和createWebHashHistory()）
  history: createWebHashHistory(),
  // 路由数组
  routes: constantRoutes,
  // 滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});

// 前置路由
router.beforeEach(async (to, from, next) => {
  nprogress.start();
  const token = userStore.token;
  console.log('路由拦截器token:', userStore.token);
  const username = userStore.username;
  if (token) {
    console.log('okay');
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      if (username) {
        next();
      } else {
        try {
          await userStore.userInfoAction();
          next({ ...to });
        } catch (err) {
          await userStore.userLogoutAction();
          // 重定向到哪里
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    console.log('fail');
    if (to.path == "/login") {
      next();
    } else {
      // 重定向到哪里
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});

// 后置路由
router.afterEach((to, from, next) => {
  nprogress.done();
});

// 向外暴露
export default router;
